<template>
  <div>
    <BasicModal
      @register="ruleRegisterModal"
      v-bind="$attrs"
      :helpMessage="['提示1', '提示2']"
      @ok="okClick"
    >
      <BasicForm @register="ruleRegisterForm" />
    </BasicModal>
  </div>
</template>

<script setup lang="ts">
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';
  import {
    getCustomersList,
    shareCustomers,
    noShareCustomers,
  } from '/@/api/thingsborad/dashboards/dashboard';
  import { ref } from 'vue';
  let emit = defineEmits(['closeShareFlag']);
  let addSchemas: FormSchema[] = [
    {
      field: 'customers',
      component: 'Select',
      label: '已分配的客户',
    },
  ];
  let dashboardInfo = ref<any>();
  const [ruleRegisterModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    dashboardInfo.value = data;
    let params: any = {
      pageSize: 50,
      page: 0,
      sortProperty: 'title',
      sortOrder: 'ASC',
    };
    let customersList = await getCustomersList(params);
    let selectData: Array<any> = [];
    customersList.data.forEach((item) => {
      selectData.push({
        value: item.id.id,
        label: item.name,
      });
    });
    

    updateSchema({
      field: 'customers',
      componentProps: {
        mode: 'multiple',
        options: selectData,
        placeholder: '实体列表',
      },
    });
    if (data.assignedCustomers !== '--') {
      setFieldsValue({
        customers: data.info.assignedCustomers[0].customerId.id,
      });
    }
    
    setModalProps({
      loading: false,
      confirmLoading: false,
      ...modalStyleSetting,
    });
  });

  const [ruleRegisterForm, { validate, resetFields, updateSchema, setFieldsValue }] = useForm({
    layout: 'vertical',
    schemas: addSchemas,
    actionColOptions: {
      span: 24,
    },
    showActionButtonGroup: false,
    showSubmitButton: true,
    showResetButton: false,
    ...modalFormStyleSetting,
  });

  const okClick = async () => {
    let validateData = await validate();
    let data: Array<any> = [];

    if (typeof validateData.customers === 'string') {
      data.push(validateData.customers);
    } else {
      data = validateData.customers;
    }
    let params: any = {
      id: dashboardInfo.value.id,
      data,
    };
    if (validateData.customers.length !== 0) {
      await shareCustomers(params);
    } else {
      await noShareCustomers(dashboardInfo.value.id);
    }
    closeModal();
    emit('closeShareFlag', true);
  };
</script>
